package cn.sail.shiroAuthenticator.security;

import cn.sail.shiroAuthenticator.pojo.entity.Permission;
import cn.sail.shiroAuthenticator.pojo.entity.Role;
import cn.sail.shiroAuthenticator.pojo.entity.User;
import cn.sail.shiroAuthenticator.service.PermissionService;
import cn.sail.shiroAuthenticator.service.RoleService;
import cn.sail.shiroAuthenticator.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义Realm
 */

public class CustomRealmWithMD5FormDB extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(CustomRealmWithMD5FormDB.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;



    /**
     * 授权验证
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.debug("开始权限认证");
        System.out.println("开始权限认证");
        User userSession = (User) principalCollection.getPrimaryPrincipal();
        //从数据库获取角色信息
        List<Role> roles = roleService.getRolesByUserId(userSession.getId());
        List<String> roleCollect = roles.stream().map(Role::getEnname).collect(Collectors.toList());
        //从数据库获取权限信息
        List<Permission> permissions = permissionService.getPermissionsByUserId(userSession.getId());
        List<String> permissionCollect = permissions.stream().map(Permission::getEnname).collect(Collectors.toList());

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        //封装用户角色列表
        authorizationInfo.addRoles(roleCollect);
        //封装用户权限列表
        authorizationInfo.addStringPermissions(permissionCollect);
        return authorizationInfo;
    }



    /**
     * 身份认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.debug("开始用户认证");
        System.out.println("开始用户认证");
        //获取请求用户名信息
        String tokenUserName = (String) authenticationToken.getPrincipal();
        //判断用户是否存在
        User dbUser = userService.selectByUserName(tokenUserName);



        //用户不存在
        if(dbUser == null){
            logger.warn("doGetAuthenticationInfo failed. 用户不存在. tokenUserName:{}", tokenUserName);
            return null;
        }

        //用户存在，返回用户信息
        //密码MD5加密后，支持加盐
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(dbUser, dbUser.getPassword(), ByteSource.Util.bytes(dbUser.getSalt()), "testRealm");
        return authenticationInfo;

    }
}
